value, pushed back between lo and hi if it has wandered outside them - keeping a position inside a room, a health bar between 0 and its maximum, anything with a hard floor and ceiling.
clamp(value, lo, hi) -> real| Name | Type |
|---|---|
value | real |
lo | real |
hi | real |
real
value, pushed back between lo and hi if it has wandered outside either one - otherwise value itself, unchanged. The usual shape underneath this: max(lo, min(hi, value)), spelled out as one call that says what it means.
Anything with a hard floor and a hard ceiling reaches for this - a position kept inside a room, a health bar that cannot go below 0 or above its own maximum, a zoom level with a closest and a furthest setting.
clamp hands back a real, even when the number you gave it was whole. If the thing you are clamping is counted - a slot number, a level, a lives count - and should stay a whole number, use clamp_int instead.
x = clamp(x, 0, room_width());
y = clamp(y, 0, room_height());Keeps this object from wandering past the edges of the current room - a GBML room is counted from its top-left corner (0, 0), so its left and top edges are 0 and its right and bottom edges are room_width and room_height. Written out by hand (as it was before clamp existed) this needs four separate if statements, one per edge; clamp says the same thing in one line per axis.
lo and hi can be given in either orderA reversed pair (lo bigger than hi) is swapped before anything else happens, so clamp always returns a value between whichever two bounds were actually given - never a crash, and never a wrong answer for getting the order backwards. This matches roll_int's own "a reversed range is answered as the same range read the other way round" rule, not a coincidence - the same standing idea applied to a different function.
A couple of comparisons - cheap enough for every frame, on every axis a position/value needs bounding on.
lo and hi may be given in either order - a reversed pair is swapped first, so this always returns a value between whichever two bounds were given, never a crash and never an unpredictable answer (the same "clamp/absorb, never assert" posture roll_int already applies to a reversed range). A couple of comparisons - cheap enough for every frame.